package com.stu.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * // 前置通知,后置通知,后置返回通知,异常通知
 * @author zy
 * @date 2025/3/31
 */
//@Component
@Aspect  // 标注切面类,切面 = 通知 + 切入点
public class LogAspect {
    @Pointcut("execution(* com.stu.dao.*.*(..))")
    public void pointcut() {}

    @Before("execution(int com.stu.dao.UserDaoImpl.addUser(int,int))")
    public void before(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();  // 方法名
        Object[] args = joinPoint.getArgs();  // 方法数组
        System.out.println("方法名:"+methodName+", 参数:"+ Arrays.toString(args));
    }

    @After("pointcut()")  // 出现异常也能执行
    public void after(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("方法名:"+methodName+", 参数:"+ Arrays.toString(args));
    }

    @AfterReturning(value = "execution(* com.stu.dao.*.*(..))",returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("方法名:"+methodName+", 参数:"+ Arrays.toString(args)+", 返回值:"+result);
    }

    @AfterThrowing(value = "pointcut()", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Exception e) {
        String methodName = joinPoint.getSignature().getName();
        System.out.println(methodName+"异常信息: "+e.getMessage());
    }
}
